<?php

class AdminController extends Plugin {
	
    public function __construct() {
        parent::__construct();
        if (!$this->session->is_set('user_id') || !$this->session->get('user_id')) $this->adminMsg('请登录以后再操作', url('admin/login'));
		$menu = array(
		    array('index',    '数据调用'),
			array('cats',     '商品类目id查看'),
			array('setting',  '账户配置'),
		);
		$this->assign('menu', $menu);
    }
	
	public function indexAction() {
	    $cachesize = 0;
		$dir = APP_ROOT . 'cache' . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'taobaoke' . DIRECTORY_SEPARATOR;
		if ($this->isPostForm()) {
		    $this->delDir($dir);
		    $this->adminMsg('操作成功', purl('admin/'), 3, 1, 1);
		}
		$data = is_dir($dir) ? file_list::get_file_list($dir) : 0;
		if ($data) {
		    foreach ($data as $file) {
			    $cachesize += filesize($dir . $file);
			}
		}
		$this->assign(array(
		    'cachesize' => formatFileSize($cachesize),
		));
	    $this->display('list');
	}
	
	/*
	 * 配置
	 */
	public function settingAction() {
	    if ($this->isPostForm()) {
		    $data  = $app = array();
			$data['username']  = $this->post('username');
			$data['cachetime'] = $this->post('cachetime');
			$data['error']     = $this->post('error');
			$data['listtpl']   = $this->post('listtpl');
			$data['showtpl']   = $this->post('showtpl');
			$users = $this->post('users');
			if ($users) {
			    foreach ($users['a'] as $k=>$ak) {
				    if ($ak && $users['s'][$k]) $app[] = array('a'=>$ak, 's'=>$users['s'][$k]);
				}
			}
			$data['appusers'] = $app;
			$this->cache->set('taobaoke', $data);
			$this->adminMsg('操作成功', purl('admin/setting'), 3, 1, 1);
		}
		$this->assign(array(
		    'data' => $this->setting,
		));
	    $this->display('setting');
	}
	
	/*
	 * 获取栏目
	 */
	public function getcatsAction() {
	    if ($this->get('submit')) {
			$data  = _get_taobao_cats();
			if (empty($data)) $this->adminMsg('没有获取到商品类目，请检查配置!');
			$list  = array();
			$count = 0;
			foreach ($data as $c) {
			    $k = $c['cid'];
				$c['is_top'] = 1;
			    $list[$k] = $c;
				$count ++;
				if ($c['is_parent'] == true) {
				    $data1 = _get_taobao_cats($c['cid']);
					if ($data1 && is_array($data1)) {
					    foreach ($data1 as $c1) {
						    $list[$c1['cid']] = $list[$k]['list'][$c1['cid']] = $c1;
				            $count ++;
						}
					}
				}
			}
			$this->cache->set('taobaoke_cats', $list);
			$this->adminMsg('类目获取成功(#' . $count . ')!');
		} else {
		    $this->adminMsg('正在获取商品类目，请稍后....', purl('admin/getcats', array('submit'=>1)), 1, 1, 2);
		}
	}
	
	/*
	 * 商品栏目
	 */
	public function catsAction() {
	    if ($this->isPostForm()) {
		    $this->adminMsg('正在获取商品类目，请稍后....', purl('admin/getcats', array('submit'=>1)), 1, 1, 2);
		}
		$this->assign('data', get_taobao_cats());
		$this->display('cats');
	}
	
}